import jwt from 'jsonwebtoken';
import { JwtPayload } from '../types';

// JWT密钥
const JWT_SECRET: string = process.env.JWT_SECRET || 'your-secret-key';

// 生成JWT token
export const generateToken = (payload: Omit<JwtPayload, 'iat' | 'exp'>): string => {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: '24h' });
};

// 验证JWT token
export const verifyToken = (token: string): JwtPayload | null => {
  try {
    const decoded = jwt.verify(token, JWT_SECRET) as JwtPayload;
    return decoded;
  } catch (error) {
    return null;
  }
};

// 从Authorization header提取token
export const extractTokenFromHeader = (authHeader?: string): string | null => {
  if (!authHeader) return null;
  
  const match = authHeader.match(/^Bearer (.+)$/);
  return match ? match[1] : null;
}; 